package com.ysx.attendance.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ysx.attendance.bean.ClassBean;
import com.ysx.attendance.bean.DelayBean;
import com.ysx.attendance.dto.CakeDTO;
import com.ysx.attendance.dto.PageDTO;
import com.ysx.attendance.service.ClassService;
import com.ysx.attendance.service.impl.ClassServiceImpl;
import com.ysx.base.BaseBean;
import com.ysx.base.BaseController;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.lang.reflect.GenericDeclaration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name="ClassController",urlPatterns="/class/find.do")
public class ClassController extends BaseController {

    private ClassService classService= new ClassServiceImpl();

    @Override
    public void service(ServletRequest servletRequest, ServletResponse response) throws ServletException, IOException {
        String method = servletRequest.getParameter("method");
        List<ClassBean> classList =new ArrayList<ClassBean>();
        if("all".equals(method)){
            findAllClass(servletRequest,response);
        }else if("one".equals(method)){
            findOneClass(servletRequest, response);
        }else if("delay".equals(method)){

            // 获取迟到的考勤数据 没有分页

            List<DelayBean> delayList = classService.getDelayList();
            printData(true,delayList,200,response);

        }else if("page".equals(method)){

            // 获取迟到的考勤数据 没有分页

            //第几页  从1开始
            Integer currentPage = Integer.parseInt(servletRequest.getParameter("currentPage"));

            // 1页有多少条
            Integer pageSize =Integer.parseInt(servletRequest.getParameter("pageSize"));

            Integer begin = (currentPage-1)*pageSize;
            List<DelayBean> delayList = classService.getDelayListPage(begin, pageSize);
            Integer counter = classService.getDelayListPageCounter();

            //封装最终的结果集
            PageDTO page= new PageDTO();
            page.setDelayList(delayList);
            page.setCounter(counter);

            printData(true,page,200,response);


        }else if("delete".equals(method)){

            // 获取迟到的考勤数据

            // 拿到ids 如何拿post请求的参数

            /*InputStreamReader insr = new InputStreamReader(servletRequest.getInputStream(),"utf-8");
            String result = "";
            int respInt = insr.read();
            while(respInt!=-1) {
                result +=(char)respInt;
                respInt = insr.read();
            }
            JSONObject jsonRet = JSONObject.parseObject(result);
            System.out.println(jsonRet);*/

            BufferedReader reader = servletRequest.getReader();

            String ss = reader.readLine();
            System.out.println(ss);


            JSONObject abc = JSON.parseObject(ss);
            JSONArray array = (JSONArray)abc.get("ids");

            List<Integer> ids= new ArrayList<>();
            try{
                for(Object element:array){
                    ids.add((Integer) element);
                }

                System.out.println(ids);

            }catch (Exception exception){
                System.out.println(exception);
            }


            /*JSONObject jsonObject= new JSONObject();
            Object ids1 = jsonObject.get("ids");
            Integer[] ids2 = jsonObject.getObject("ids", Integer[].class);
            JSONObject rs = jsonObject.getJSONObject(ss);
            Object ids = rs.get("ids");
            Integer[] rsss= (Integer[])ids;
            System.out.println(rsss);*/


            // delete from oa_attendance_t where id in(320,360,370);
            classService.deleteByIds(ids);

            printData(true,null,200,response);

        }else if("cake".equals(method)){
            // 专门处理http协议的请求
            HttpServletRequest request= (HttpServletRequest)servletRequest;
            HttpSession session = request.getSession();
            Integer userId = (Integer)session.getAttribute("userId");

            List<CakeDTO> cakeList= classService.getCake(userId);

            // boolean check=(cakeList!=null && cakeList.size()>=0)?true:false;

            printData(true,cakeList,200,response);

        }else if("insert".equals(method)){

            // 做的任何事情=业务逻辑  把这些学生保存到数据库中  所有的数据都封装在request中  容器=管家

            // 1 把所有学生的id数据拿到和哪天迟到的数据拿到 [10010 10020]

            String[] ids = servletRequest.getParameterValues("ids");

            //迟到日期
            String delayDate = servletRequest.getParameter("delayDate");

            // 2 调用Service把id保存到数据库中

            int rs = classService.saveData(ids,delayDate);
            // 3 拿到Service的结果 然后返回JSON数据给前端?

            boolean check=rs==1?true:false;

            printData(check,null,500,response);
        }
    }

    private void findAllClass(ServletRequest servletRequest,ServletResponse response) throws IOException {
        List<ClassBean> classList;

        // 专门处理http协议的请求
        HttpServletRequest request= (HttpServletRequest)servletRequest;

        //除了登陆成功的地方必须写true 其他所有拿杯子session的地方都不能写ture
        HttpSession session = request.getSession();

        // userId=10010 从杯子中拿userId  这个杯子到处都可以用
        Integer userId = (Integer)session.getAttribute("userId");

        //现在先写死 后面写或 后面这个值从session中取
        //Integer userId=Integer.parseInt(request.getParameter("userId"));

        classList = classService.findClassList(userId);

        Map<String,Object> map = new HashMap<>();

        boolean check=(classList == null || classList.size()==0)?false:true;

        printData(check,classList,404,response);
    }

    private void findOneClass(ServletRequest request, ServletResponse response) throws IOException {
        // 重点: 在控制层中只做2件事  分层=分工
        //1 接受参数
        String ps = request.getParameter("classId");
        if(null != ps && "".equals(ps) && "null".equals(ps) && "".equals(ps.trim())){
            return;
        }
        Integer classId= Integer.parseInt(ps);
        String studentName= request.getParameter("studentName");

        ClassBean classBean=null;
        if("".equals(studentName)){
            classBean =classService.findTeacherAndStudentListByClassId(classId);
        }else{
            classBean =classService.findTeacherAndStudentListByClassIdAndStudentName(classId,studentName);
        }

        //2 调用Service拿到结果并返回给前端  注意:不去调用service 然后在Controller把代码写完
        List<ClassBean> classList = new ArrayList<>();
        classList.add(classBean);
        boolean check=(classBean == null)?false:true;
        printData(check,classList,200,response);
    }
}
